package com.itsm.xkitsm.liferoot.ems;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ExpressInfoService {

	public ExpressInfo getResponse(String number, String type) {
		String reulst = null;
		ExpressInfo express = null;
		try {
			String url = Constant.Express.EXPRESS_API_URL.replace("post_id",
					number.toUpperCase()).replace("name", type);
			reulst = SearchTools.getResponseRelsut(url,
					Constant.Express.FORMAT_TYPE);
			express = parseJSON(reulst);
		} catch (IOException e) {
			StateCode.express_search_status = Constant.Express.NET_LINK_ERROR;
			return null;
		} catch (JSONException e) {
			StateCode.express_search_status = Constant.Express.NET_LINK_ERROR;
			return null;
		}
		catch (IllegalArgumentException e) {
			StateCode.express_search_status = Constant.Express.ID_NO_EXIST;
			return null;
		}
		StateCode.express_search_status = Constant.Express.SUCCESS_FULL;
		return express;
	}

	private ExpressInfo parseJSON(String jsonStr) throws JSONException {
		ExpressInfo express = new ExpressInfo();
		JSONObject jsonObj = new JSONObject(jsonStr);
		if(jsonObj.getString("status").equals("0")){
			throw new IllegalArgumentException();
		}
		JSONArray data =  jsonObj.getJSONArray("data");
		StringBuffer buffer=new StringBuffer();
		for(int i=0;i<data.length();i++){
			buffer.append(data.getJSONObject(i).getString("time").replace("&nbsp;", " ")).append(":  ").append(data.getJSONObject(i).getString("context").replace("&nbsp;", " ")).append("\n");
			
		}
		express.setOpt_message(buffer.toString());
		return express;
	}

}
